import { useState } from 'react';
import { Download, Settings, Video, FileText, Zap, HardDrive } from 'lucide-react';
import { useAppDispatch, useAppSelector } from '@/store';
import { showToast } from '@/store/slices/uiSlice';
// import { exportVideo } from '@/services/video';

interface ExportPanelProps {
  className?: string;
}

interface ExportPreset {
  id: string;
  name: string;
  description: string;
  icon: React.ComponentType<any>;
  settings: {
    format: string;
    resolution: string;
    bitrate: number;
    frameRate: number;
    quality: string;
  };
}

const ExportPanel: React.FC<ExportPanelProps> = ({ className }) => {
  const dispatch = useAppDispatch();
  const { clips, duration } = useAppSelector(state => state.timeline);

  const [exporting, setExporting] = useState(false);
  const [exportProgress, setExportProgress] = useState(0);
  const [selectedPreset, setSelectedPreset] = useState<string>('high');
  const [customSettings, setCustomSettings] = useState({
    format: 'mp4',
    resolution: '1920x1080',
    bitrate: 8000,
    frameRate: 30,
    quality: 'high',
    outputPath: '',
    fileName: 'edited_video',
  });

  // 导出预设
  const exportPresets: ExportPreset[] = [
    {
      id: 'high',
      name: '高质量',
      description: '最佳画质，适合专业用途',
      icon: Video,
      settings: {
        format: 'mp4',
        resolution: '1920x1080',
        bitrate: 12000,
        frameRate: 30,
        quality: 'high',
      },
    },
    {
      id: 'balanced',
      name: '平衡',
      description: '画质和文件大小的最佳平衡',
      icon: Zap,
      settings: {
        format: 'mp4',
        resolution: '1280x720',
        bitrate: 5000,
        frameRate: 30,
        quality: 'medium',
      },
    },
    {
      id: 'mobile',
      name: '移动设备',
      description: '适合在手机上播放',
      icon: FileText,
      settings: {
        format: 'mp4',
        resolution: '854x480',
        bitrate: 2000,
        frameRate: 30,
        quality: 'medium',
      },
    },
    {
      id: 'web',
      name: '网络分享',
      description: '适合在线分享和流媒体',
      icon: HardDrive,
      settings: {
        format: 'mp4',
        resolution: '1280x720',
        bitrate: 3000,
        frameRate: 25,
        quality: 'medium',
      },
    },
  ];

  const handleExport = async () => {
    if (clips.length === 0) {
      dispatch(
        showToast({
          type: 'error',
          title: '导出失败',
          message: '请先添加视频剪辑到时间线',
        })
      );
      return;
    }

    setExporting(true);
    setExportProgress(0);

    try {
      // const selectedPresetConfig = exportPresets.find(p => p.id === selectedPreset);
      // const exportSettings = {
      //   ...(selectedPresetConfig?.settings || exportPresets[0].settings),
      //   ...customSettings
      // };

      // 模拟导出过程
      const interval = setInterval(() => {
        setExportProgress(prev => {
          if (prev >= 100) {
            clearInterval(interval);
            setExporting(false);

            // 导出完成
            dispatch(
              showToast({
                type: 'success',
                title: '导出成功',
                message: '视频导出完成！',
              })
            );
            return 100;
          }
          return prev + 1;
        });
      }, 50);

      // 实际导出逻辑（调用Tauri后端）
      // await exportVideo({
      //   timeline: clips,
      //   settings: exportSettings,
      //   outputPath: customSettings.outputPath || './exports'
      // });
    } catch (error) {
      console.error('导出失败:', error);
      dispatch(
        showToast({
          type: 'error',
          title: '导出失败',
          message: '视频导出失败，请重试',
        })
      );
      setExporting(false);
    }
  };

  const handleCustomSettingChange = (key: string, value: any) => {
    setCustomSettings(prev => ({
      ...prev,
      [key]: value,
    }));
  };

  const renderExportSettings = () => {
    return (
      <div className='export-settings'>
        <div className='setting-group'>
          <label className='setting-label'>输出格式</label>
          <select
            value={customSettings.format}
            onChange={e => handleCustomSettingChange('format', e.target.value)}
            className='setting-select'
          >
            <option value='mp4'>MP4</option>
            <option value='avi'>AVI</option>
            <option value='mov'>MOV</option>
            <option value='webm'>WebM</option>
          </select>
        </div>

        <div className='setting-group'>
          <label className='setting-label'>分辨率</label>
          <select
            value={customSettings.resolution}
            onChange={e => handleCustomSettingChange('resolution', e.target.value)}
            className='setting-select'
          >
            <option value='3840x2160'>4K (3840x2160)</option>
            <option value='1920x1080'>1080p (1920x1080)</option>
            <option value='1280x720'>720p (1280x720)</option>
            <option value='854x480'>480p (854x480)</option>
            <option value='640x360'>360p (640x360)</option>
          </select>
        </div>

        <div className='setting-group'>
          <label className='setting-label'>比特率</label>
          <div className='bitrate-controls'>
            <input
              type='range'
              min={500}
              max={20000}
              step={100}
              value={customSettings.bitrate}
              onChange={e => handleCustomSettingChange('bitrate', Number(e.target.value))}
              className='bitrate-slider'
            />
            <span className='bitrate-value'>{customSettings.bitrate} kbps</span>
          </div>
        </div>

        <div className='setting-group'>
          <label className='setting-label'>帧率</label>
          <select
            value={customSettings.frameRate}
            onChange={e => handleCustomSettingChange('frameRate', Number(e.target.value))}
            className='setting-select'
          >
            <option value={24}>24 fps</option>
            <option value={25}>25 fps</option>
            <option value={30}>30 fps</option>
            <option value={50}>50 fps</option>
            <option value={60}>60 fps</option>
          </select>
        </div>

        <div className='setting-group'>
          <label className='setting-label'>文件名</label>
          <input
            type='text'
            value={customSettings.fileName}
            onChange={e => handleCustomSettingChange('fileName', e.target.value)}
            className='setting-input'
            placeholder='请输入文件名'
          />
        </div>
      </div>
    );
  };

  const renderExportInfo = () => {
    const estimatedSize = ((customSettings.bitrate * duration) / 8 / 1024).toFixed(1); // 估算文件大小

    return (
      <div className='export-info'>
        <div className='info-item'>
          <span className='info-label'>项目时长:</span>
          <span className='info-value'>{Math.floor(duration)} 秒</span>
        </div>
        <div className='info-item'>
          <span className='info-label'>剪辑数量:</span>
          <span className='info-value'>{clips.length} 个</span>
        </div>
        <div className='info-item'>
          <span className='info-label'>预计文件大小:</span>
          <span className='info-value'>{estimatedSize} MB</span>
        </div>
      </div>
    );
  };

  return (
    <div className={`export-panel ${className || ''}`}>
      <div className='panel-header'>
        <h3 className='panel-title'>
          <Download size={20} />
          导出视频
        </h3>
        <p className='panel-description'>选择导出设置并开始导出</p>
      </div>

      {clips.length === 0 ? (
        <div className='export-empty'>
          <Video size={48} className='empty-icon' />
          <p className='empty-text'>时间线为空</p>
          <p className='empty-subtext'>请先添加视频剪辑到时间线</p>
        </div>
      ) : (
        <>
          {/* 导出预设 */}
          <div className='export-presets'>
            <h4 className='presets-title'>导出预设</h4>
            <div className='presets-grid'>
              {exportPresets.map(preset => {
                const PresetIcon = preset.icon;
                return (
                  <div
                    key={preset.id}
                    className={`preset-card ${selectedPreset === preset.id ? 'selected' : ''}`}
                    onClick={() => setSelectedPreset(preset.id)}
                  >
                    <div className='preset-icon'>
                      <PresetIcon size={24} />
                    </div>
                    <div className='preset-info'>
                      <h5 className='preset-name'>{preset.name}</h5>
                      <p className='preset-description'>{preset.description}</p>
                    </div>
                    <div className='preset-settings'>
                      <span className='preset-resolution'>{preset.settings.resolution}</span>
                      <span className='preset-bitrate'>{preset.settings.bitrate}kbps</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* 自定义设置 */}
          <div className='custom-settings'>
            <h4 className='settings-title'>
              <Settings size={16} />
              自定义设置
            </h4>
            {renderExportSettings()}
          </div>

          {/* 导出信息 */}
          {renderExportInfo()}

          {/* 导出按钮 */}
          <div className='export-actions'>
            <button className='export-button' onClick={handleExport} disabled={exporting}>
              {exporting ? (
                <>
                  <div className='export-spinner'></div>
                  导出中... {exportProgress}%
                </>
              ) : (
                <>
                  <Download size={16} />
                  开始导出
                </>
              )}
            </button>

            {/* 进度条 */}
            {exporting && (
              <div className='export-progress'>
                <div className='progress-bar' style={{ width: `${exportProgress}%` }} />
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
};

export default ExportPanel;
